package com.thememaker.lockstyle;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXDatePicker;
import com.jfoenix.controls.JFXTimePicker;
import com.jfoenix.converters.base.NodeConverter;
import com.thememake.Constants;
import com.thememake.common.Context;
import com.thememake.common.controller.BaseController;
import com.thememake.entity.ThemeFileInfo;
import com.thememake.ui.CtsFileChooser;
import com.thememake.ui.R;
import com.thememake.ui.Toast;
import com.thememake.ui.dialog.AlertDialog;
import com.thememake.ui.dialog.ProgressDialog;
import com.thememake.ui.dialog.SBTFxDialog;
import com.thememake.util.FileUtils;
import com.thememake.util.xml.bean.ModelItem;
import com.thememake.util.xml.fontcolor.ReadXmlUtils;
import com.thememaker.lockstyle.bean.animation.Rotation;
import com.thememaker.lockstyle.bean.command.IntentCommand;
import com.thememaker.lockstyle.bean.ui.BaseView;
import com.thememaker.lockstyle.control.LayoutComponentUtils;
import com.thememaker.lockstyle.parsii.ExpressionUtils;
import com.thememaker.util.*;
import com.thememaker.util.packager.LockScreenCheckUtils;
import com.thememaker.util.packager.LockScreenPackager;
import javafx.animation.SequentialTransition;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.*;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.*;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.List;

import static com.thememaker.lockstyle.AnimationUtils.initRotationAnimation;

/**
 * Created by jiajun.jiang on 2018/2/23.
 */
public class LockstyleMainController extends BaseController {

    private ThemeFileInfo themeFileInfo;
    private Path lockscreenPath;
    private Stage primaryStage;
    private Boolean res = true;
    int count = 0;

    private LockstyleCustomTimeDialog lockstyleCustomTimeDialog = new LockstyleCustomTimeDialog();

    @FXML
    private ScrollPane rightAnchorPane, rightrightPane, lockCenterSP;
    @FXML
    private VBox leftAnchorPane, leftFileAnchorPane, lockShowVb;
    @FXML
    private AnchorPane centerAnchorPane;
    @FXML
    private TextArea editTextArea;
    @FXML
    private Button editTextAreaBtn;
    @FXML
    private BorderPane borderPane;
    @FXML
    private SplitPane lockSplitPane, centerSplitPane;

    @FXML
    private JFXButton btnMakeLockScreen, btnPackageLockScreen, btnRefLockScreen, btnStartAnimation, btnSave,
            btnStatus, btnNewWidget, btnSwitchingTime;//btnChoseLockScreen,btnImportPsd，vivoTo360, btnVivoToOppo, btnWei, btnOpenPsdDir, btnOpenErrFile

    @FXML
    private StackPane stackDpi0, stackDpi1;
    @FXML
    private ComboBox comboDpi1;
    @FXML
    private TabPane tabPane;
    @FXML
    private Tab tab1, tab2, tab0;
    @FXML
    private SplitPane splitPane;
    @FXML
    private MenuBar menuAll;
    private LockstyleShowUtils lockstyleShowUtils;
    private LockStyleCenterEditUtils lockStyleCenterEditUtils;
    private LockStyleCenterLeftEditUtils lockStyleCenterLeftEditUtils;
    private LockstyleCenterBottomArea lockstyleCenterBottomArea;
    private LockstyleControlUtils lockstyleControlUtils;
    private LockstyleBottomUtils lockstyleBottomUtils;
    private boolean isPlayAnimation = true;
    private boolean isEdit = true;
    private boolean istime = true;
    private int buttonSize = 15;
    public static Color buttonColor = Color.web("#716A94");
    public SequentialTransition sequentialTransition;
    private ExpressionUtils expressionUtils;

    private int screen_height = 1920;
    private int screen_width = 1080;
//    private boolean head_judge = true;

    private MenuItem openErrFile = new MenuItem("打开错误日志");

    public SplitPane getCenterSplitPane() {
        return centerSplitPane;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        lockCenterSP.setStyle("-fx-padding: 0;-fx-focus-traversable: false;");
//        leftAnchorPane.setStyle("-fx-padding: 0;-fx-focus-traversable: false;");
//        rightAnchorPane.setStyle("-fx-padding: 0;-fx-focus-traversable: false;");
    }

    private void initShowLock() {
        isPlayAnimation = true;
        isEdit = true;
        btnStartAnimation.setDisable(true);
        btnStartAnimation.setGraphic(SVGLoadUtils.getInstance().getPauseSVG(buttonSize, buttonColor));
        btnSwitchingTime.setGraphic(SVGLoadUtils.getInstance().getTimeXMLSVG(buttonSize, buttonColor));
        btnStatus.setGraphic(SVGLoadUtils.getInstance().getEyeSVG(buttonSize, buttonColor));
        btnRefLockScreen.setGraphic(SVGLoadUtils.getInstance().getRefreshSVG(buttonSize, buttonColor));
        lockstyleShowUtils.showLockscreen();

    }

    private void initLeft() {
        Text text = new Text();
        text.setFont(new Font(12));
        text.setWrappingWidth(240);
        Text titleText = new Text();
        titleText.setWrappingWidth(240);
        titleText.setFont(new Font(16));
        Path configPath = Paths.get(themeFileInfo.getThemeDir().getPath(), themeFileInfo.getThemeType(), ThemeFileInfo.LOCKSTYLE_NAME, "lockstyleConfig.json");
        if (Files.exists(configPath)) {
            String str = null;
            try {
                str = new String(Files.readAllBytes(configPath), "UTF-8");
                ModelItem lockScreenModelExplain = new Gson().fromJson(str,
                        new TypeToken<ModelItem>() {
                        }.getType());
                titleText.setText("制作说明：" + lockScreenModelExplain.getTitle().replace("\\n", "\n"));
                System.out.println("titleText-------------------------->>>>>>>>>>>>>>>" + lockScreenModelExplain.getTitle().replace("\\n", "\n"));
                text.setText(lockScreenModelExplain.getDescribe().replace("\\n", "\n"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        titleText.setId("diy-fontColor");
        text.setId("diy-fontColor");
        leftAnchorPane.getChildren().addAll(titleText, text);
        leftFileAnchorPane.getChildren().addAll(filePane());
    }

    private StackPane filePane() {
        StackPane stackPane = new StackPane();
        Label text = new Label("");
        text.setId("diy-fontColor");
        stackPane.getChildren().addAll(text);
        return stackPane;
    }

    private void initButton() {

//        HBox.setMargin(stackDpi0, new Insets(0, 10, 0, 10));
        HBox.setMargin(stackDpi1, new Insets(0, 10, 0, 10));
        stackDpi1.getChildren().setAll(SVGLoadUtils.getInstance().getHeightDpiSVG(buttonSize, buttonColor));
        comboDpi1.getItems().addAll(1920, 2160, 2280, 2340);

        comboDpi1.getSelectionModel().select(0);
        comboDpi1.showingProperty().addListener((observable, oldValue, newValue) -> {
            if (!newValue) {
                int selectNum = comboDpi1.getSelectionModel().getSelectedIndex();
                switch (selectNum) {
                    case 0:
                        screen_height = 1920;
                        expressionUtils = ExpressionUtils.getInstance(screen_width, screen_height);
                        lockstyleShowUtils.setExpressionUtils(expressionUtils);
                        lockStyleCenterEditUtils.setScreen_height(1920);
                        lockstyleCenterBottomArea.setScreen_height(1920);
                        initRightView();
                        break;
                    case 1:
                        screen_height = 2160;
                        expressionUtils = ExpressionUtils.getInstance(screen_width, screen_height);
                        lockstyleShowUtils.setExpressionUtils(expressionUtils);
                        lockStyleCenterEditUtils.setScreen_height(2160);
                        lockstyleCenterBottomArea.setScreen_height(2160);
                        initRightView();
                        break;
                    case 2:
                        screen_height = 2280;
                        expressionUtils = ExpressionUtils.getInstance(screen_width, screen_height);
                        lockstyleShowUtils.setExpressionUtils(expressionUtils);
                        lockStyleCenterEditUtils.setScreen_height(2280);
                        lockstyleCenterBottomArea.setScreen_height(2280);
                        initRightView();
                        break;
                    case 3:
                        screen_height = 2340;
                        expressionUtils = ExpressionUtils.getInstance(screen_width, screen_height);
                        lockstyleShowUtils.setExpressionUtils(expressionUtils);
                        lockStyleCenterEditUtils.setScreen_height(2340);
                        lockstyleCenterBottomArea.setScreen_height(2340);
                        initRightView();
                        break;
                    default:
                        break;
                }
                LayoutComponentUtils.screen_heigth = screen_height;
                lockstyleShowUtils.updateRightPreview();
                lockstyleControlUtils.update();
            }
        });

        btnRefLockScreen.setDisableVisualFocus(true);
        btnPackageLockScreen.setDisableVisualFocus(true);
        btnMakeLockScreen.setDisableVisualFocus(true);
        btnStartAnimation.setDisableVisualFocus(true);
        btnSave.setDisableVisualFocus(true);
        btnStatus.setDisableVisualFocus(true);
        btnSwitchingTime.setDisableVisualFocus(true);
        btnSwitchingTime.setTooltip(new Tooltip("自定义时间格式"));
        btnRefLockScreen.setTooltip(new Tooltip("刷新锁屏"));
        btnPackageLockScreen.setTooltip(new Tooltip("打包锁屏"));
        btnMakeLockScreen.setTooltip(new Tooltip("打开制作路径"));
        btnStartAnimation.setTooltip(new Tooltip("启动动画"));
        btnSave.setTooltip(new Tooltip("保存"));
        btnStatus.setTooltip(new Tooltip("预览模式"));
        btnStartAnimation.setDisable(true);


        initButtonFocusEffect(btnRefLockScreen, btnRefLockScreen.getStyle());
        initButtonFocusEffect(btnPackageLockScreen, btnPackageLockScreen.getStyle());
        initButtonFocusEffect(btnStartAnimation, btnStartAnimation.getStyle());
        initButtonFocusEffect(btnMakeLockScreen, btnMakeLockScreen.getStyle());
        initButtonFocusEffect(btnSave, btnSave.getStyle());
        initButtonFocusEffect(btnStatus, btnStatus.getStyle());
        initButtonFocusEffect(btnSwitchingTime, btnSwitchingTime.getStyle());

        btnStartAnimation.setGraphic(SVGLoadUtils.getInstance().getPauseSVG(buttonSize, buttonColor));
        btnStatus.setGraphic(SVGLoadUtils.getInstance().getEyeSVG(buttonSize, buttonColor));
        btnRefLockScreen.setGraphic(SVGLoadUtils.getInstance().getRefreshSVG(buttonSize, buttonColor));

        btnMakeLockScreen.setGraphic(SVGLoadUtils.getInstance().getOpenFolderSVG(buttonSize, buttonColor));
        btnSave.setGraphic(SVGLoadUtils.getInstance().getSaveSVG(buttonSize, buttonColor));
        btnPackageLockScreen.setGraphic(SVGLoadUtils.getInstance().getPackageSVG(buttonSize, buttonColor));
        btnSwitchingTime.setGraphic(SVGLoadUtils.getInstance().getClockOSVG(buttonSize, buttonColor));


        btnSwitchingTime.setOnAction(event -> {
            lockstyleCustomTimeDialog.customTime();
            if (LockstyleCustomTimeDialog.arrfim) {
                if (lockstyleShowUtils != null) {
                    expressionUtils = ExpressionUtils.getInstance(screen_width, screen_height, LockstyleCustomTimeDialog.pair1);
                    lockstyleShowUtils.setExpressionUtils(expressionUtils);
                    lockstyleShowUtils.showLockscreen();
                }
            }

        });


        btnPackageLockScreen.setOnAction(event -> {
            AutoSaveUtils.getInstance(themeFileInfo).stopSave();
            lockstyleShowUtils.snapshot(centerAnchorPane, image -> {
                LockscreenPackageDialog lockscreenPackageDialog = new LockscreenPackageDialog(primaryStage, "正在为您打包，请稍等……");
                lockscreenPackageDialog.setThemeFileInfo(themeFileInfo);
                lockscreenPackageDialog.showProgressBar(new Task<Void>() {
                    @Override
                    protected Void call() throws Exception {
                        lockscreenPackageDialog.updateProgress("5%");
                        if (lockstyleShowUtils.getLockscreen() == null) {
                            LayoutComponentUtils.head_judge = false;
                            return null;
                        }
                        if (lockstyleShowUtils != null) {
                            lockstyleShowUtils.save2();
                        }
                        if (lockstyleShowUtils.getLockscreen().getVibrate() == null) {
                            LayoutComponentUtils.engine = 1;
                        }
                        new LockScreenCheckUtils(lockstyleShowUtils.getLockscreen(), themeFileInfo).checkLockscreen(lockscreenPackageDialog::printError);
                        if (!LayoutComponentUtils.content_Determine) {
                            return null;
                        }
                        lockscreenPackageDialog.updateProgress("50%");
                        try {
                            new LockScreenPackager(themeFileInfo, lockscreenPath).pack((type, path) -> {
                            }, (type, path) -> {
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        lockscreenPackageDialog.updateProgress("80%");
                        lockstyleShowUtils.savePreview(image);
                        return null;
                    }
                }, s -> {
                    if (LayoutComponentUtils.head_judge && LayoutComponentUtils.content_Determine) {
                        lockscreenPackageDialog.updateProgress("100%");
                        lockscreenPackageDialog.packageSuccess();
                        Toast.makeText(primaryStage, "打包成功，请打包主题查看", 2000);
                    } else if (!LayoutComponentUtils.head_judge) {
                        lockscreenPackageDialog.updateProgress("100%");
                        lockscreenPackageDialog.packageSuccess(LayoutComponentUtils.head_judge);
                        Toast.makeText(primaryStage, "打包失败，请检查锁屏文件!", 2000);
                    } else if (!LayoutComponentUtils.content_Determine) {
                        lockscreenPackageDialog.updateProgress("100%");
                        lockscreenPackageDialog.packageSuccess(LayoutComponentUtils.content_Determine);
                        Toast.makeText(primaryStage, "打包失败，请检查锁屏文件!", 2000);
                    }

                });
            });
        });


        btnMakeLockScreen.setPrefSize(100, 20);
        btnMakeLockScreen.setOnAction(event -> {
            try {
                Desktop.getDesktop().open(lockscreenPath.toFile());
            } catch (IOException e) {
                e.printStackTrace();
            }

        });
        List<Rotation> rotations = new ArrayList<>();
        Rotation rotation1 = new Rotation();
        rotation1.setTime("0");
        rotation1.setAngle("0");
        Rotation rotation2 = new Rotation();
        rotation2.setTime("1000");
        rotation2.setAngle("360");
        Rotation rotation3 = new Rotation();
        rotation3.setTime("100000000000000");
        rotation3.setAngle("0");
        rotations.add(rotation1);
        rotations.add(rotation2);
        rotations.add(rotation3);
        sequentialTransition = initRotationAnimation(btnRefLockScreen, rotations);
        btnRefLockScreen.setOnAction(event -> {
            sequentialTransition.play();
            if (lockstyleShowUtils != null) {
                lockstyleShowUtils.showLockscreen();
            }
        });
        btnStartAnimation.setOnAction(event -> {
            if (isEdit) {
                Toast.makeText(getApplication().getStage(), "请先启动预览模式", 1000);
                return;
            }
            if (isPlayAnimation) {
                btnStartAnimation.setGraphic(SVGLoadUtils.getInstance().getPlaySVG(buttonSize, buttonColor));
//                btnStartAnimation.setText("启动动画");
                if (lockstyleShowUtils != null) {
                    lockstyleShowUtils.stopAnimation();
                }
            } else {
                btnStartAnimation.setGraphic(SVGLoadUtils.getInstance().getPauseSVG(buttonSize, buttonColor));
//                btnStartAnimation.setText("暂停动画");
                if (lockstyleShowUtils != null) {
                    lockstyleShowUtils.startAnimation();
                }
            }
            isPlayAnimation = !isPlayAnimation;
        });
        btnSave.setOnAction(event -> {
            if (lockstyleShowUtils != null) {
                lockstyleShowUtils.save();

            }
        });
//        btnStartAnimation.setVisible(false);
        btnStatus.setOnAction(event -> {
            if (isEdit) {
                btnStatus.setGraphic(SVGLoadUtils.getInstance().getEditSVG(buttonSize, buttonColor));
                if (lockstyleShowUtils != null) {
                    lockstyleShowUtils.setEdit(false);
                    btnStartAnimation.setDisable(false);
                    lockstyleShowUtils.showLockscreen();
                }
            } else {
                btnStatus.setGraphic(SVGLoadUtils.getInstance().getEyeSVG(buttonSize, buttonColor));
                if (lockstyleShowUtils != null) {
                    lockstyleShowUtils.setEdit(true);
                    btnStartAnimation.setDisable(true);
                    lockstyleShowUtils.showLockscreen();
                }
            }
            isEdit = !isEdit;
        });
//        btnOpenPsdDir.setVisible(false);
//        if (VipControllerUtils.getInstance(themeFileInfo).canUseLockscreenPsd()) {
////
//        } else {
////            btnImportPsd.setVisible(false);
//        }


        String errorLogPath = FileUtils.getResFileOfThemeModel() + File.separator + "errorlog.xml";
        if (new File(errorLogPath).exists()) {
//            btnOpenErrFile.setVisible(true);
            openErrFile.setVisible(true);
        } else {
//            btnOpenErrFile.setVisible(false);
            openErrFile.setVisible(false);
        }
        openErrFile.setOnAction(event -> {
            try {
                Desktop.getDesktop().open(new File(errorLogPath));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

//
    }


    public void showLockStyleView(Stage primaryStage, ThemeFileInfo themeFileInfo) {
        this.themeFileInfo = themeFileInfo;
        this.primaryStage = primaryStage;
        if (themeFileInfo != null) {
            lockscreenPath = Paths.get(themeFileInfo.getThemeDir().getPath(), themeFileInfo.getThemeType(), ThemeFileInfo.LOCKSTYLE_NAME, "lockscreen");
            LayoutComponentUtils.lockscreenPath = lockscreenPath;
            System.out.println("lockscreenPath===========================" + lockscreenPath);
        }
        expressionUtils = ExpressionUtils.getInstance(screen_width, screen_height);
        lockstyleShowUtils = new LockstyleShowUtils(splitPane, leftAnchorPane, leftFileAnchorPane, centerAnchorPane, lockscreenPath, themeFileInfo, getApplication().getStage());
        LayoutComponentUtils.lockstyleShowUtils = lockstyleShowUtils;
        lockstyleShowUtils.setExpressionUtils(expressionUtils);
        lockstyleShowUtils.setLockstyleMainController(this);
        lockStyleCenterEditUtils = new LockStyleCenterEditUtils(rightAnchorPane, rightrightPane, themeFileInfo, getApplication().getStage());
        lockStyleCenterLeftEditUtils = new LockStyleCenterLeftEditUtils(rightAnchorPane, themeFileInfo);
        lockstyleControlUtils = new LockstyleControlUtils(rightAnchorPane, themeFileInfo, expressionUtils, lockstyleShowUtils);
        lockstyleCenterBottomArea = new LockstyleCenterBottomArea(editTextArea, editTextAreaBtn, themeFileInfo, lockscreenPath, getApplication().getStage(), lockstyleShowUtils);
        lockstyleShowUtils.setLockstyleCenterController(lockStyleCenterEditUtils);
        lockstyleShowUtils.setLockStyleCenterLeftEditUtils(lockStyleCenterLeftEditUtils);
        lockstyleShowUtils.setLockstyleCenterBottomArea(lockstyleCenterBottomArea);
        lockstyleShowUtils.setLockstyleControlUtils(lockstyleControlUtils);
        lockstyleShowUtils.setLockstyleShowRightEventControl(expressionUtils, getApplication().getStage(), lockStyleCenterEditUtils, lockStyleCenterLeftEditUtils, lockscreenPath);
        lockstyleShowUtils.showLockscreen();
        lockstyleBottomUtils = new LockstyleBottomUtils(splitPane, tab0, tabPane, leftFileAnchorPane, getApplication().getStage(), lockstyleShowUtils);
        lockstyleShowUtils.setLockstyleBottomUtils(lockstyleBottomUtils);
        initMenu();
        initRightView();
        initButton();
        initLeft();
        switchTabPane();

        lockCenterSP.setOnKeyPressed(event -> {
            switch (event.getCode()) {
                case LEFT:
                case UP:
                case RIGHT:
                case DOWN:
                    lockCenterSP.setVvalue(0.0);
                    lockCenterSP.setHvalue(0.0);
                    break;
                default:
                    break;
            }
        });
    }

    private void initRightView() {
        lockSplitPane.setPrefWidth(screen_width * lockstyleShowUtils.getRate() + 30);
        lockSplitPane.setPrefHeight(screen_height * lockstyleShowUtils.getRate() + 20);
        lockSplitPane.setMaxWidth(screen_width * lockstyleShowUtils.getRate() + 30);
        lockSplitPane.setMaxHeight(screen_height * lockstyleShowUtils.getRate() + 20);

        lockShowVb.setPrefWidth(screen_width * lockstyleShowUtils.getRate());
        lockShowVb.setPrefHeight(screen_height * lockstyleShowUtils.getRate());
        lockShowVb.setMaxWidth(screen_width * lockstyleShowUtils.getRate());
        lockShowVb.setMaxHeight(screen_height * lockstyleShowUtils.getRate());
    }

    public void switchTabPane() {

        tab0.setGraphic(SVGLoadUtils.getInstance().getShrink2SVG(13, Color.web("#5264AE")));
        tab0.selectedProperty().addListener(e -> {
            if (tab0.isSelected()) {
                splitPane.setDividerPositions(0.965);
            }
        });

        tab1.selectedProperty().addListener(e -> {
            if (tab1.isSelected()) {
                splitPane.setDividerPositions(0.67);
            }
        });

        tab2.selectedProperty().addListener(e -> {
            if (tab2.isSelected()) {
                splitPane.setDividerPositions(0.67);
            }
        });
    }

    private void initButtonFocusEffect(JFXButton jfxButton, String baseStyle) {
        jfxButton.setStyle("-fx-border-color: transparent;" + baseStyle);
        jfxButton.addEventHandler(MouseEvent.MOUSE_ENTERED, event -> {
            jfxButton.setStyle("-fx-border-color: #5264AE;-fx-border-radius: 3;" + baseStyle);
        });
        //鼠标离开区域
        jfxButton.addEventHandler(MouseEvent.MOUSE_EXITED, event -> {
            jfxButton.setStyle("-fx-border-color: transparent;-fx-border-radius: 3;" + baseStyle);
        });
    }


    public static long testSystem(long times) {
        long currentTime = 0;
        for (int i = 0; i < times; i++) {
            currentTime = System.currentTimeMillis();
        }
        return currentTime;
    }


    private void initMenu() {
        Menu fileMenu = new Menu("文件");
        Menu toolMenu = new Menu("工具");
        Menu helpMenu = new Menu("帮助");
        MenuItem optModule = new MenuItem("重新选择模板");
        optModule.setOnAction(event -> {
            AutoSaveUtils.getInstance(themeFileInfo).stopSave();
            SBTFxDialog.showMessageDialog(null, "重新选择模板后，之前的锁屏会被删除", "温馨提示", () -> {
                FileUtils.deleteDir(lockscreenPath.getParent().toFile());
                FileUtils.deleteDir(new File(themeFileInfo.getOutputDir(), "lockscreen"));
                new LockscreenModelChooseDialog(new Stage(), themeFileInfo).show();
                getApplication().getStage().close();
            }, () -> {
            });
        });
        MenuItem importLockscreen = new MenuItem("导入锁屏psd");
        importLockscreen.setOnAction(event -> {
            AutoSaveUtils.getInstance(themeFileInfo).stopSave();
            if (themeFileInfo.getThemeLockscreenPsdFile().exists()) {
                SBTFxDialog.showMessageDialog(getApplication().getStage(), "导入锁屏psd时，会删除当前锁屏\n并会使用psd中的锁屏进行制作！"
                        , "温馨提示", "导入", "取消", () -> {
                            ProgressDialog progressDialog = new ProgressDialog(new Task<Void>() {
                                @Override
                                protected Void call() throws Exception {
                                    new LockstylePsdUtils(themeFileInfo).importLockscreen();
                                    return null;
                                }
                            }, getApplication().getStage(), "正在导入，请稍等……");
                            progressDialog.showProgressBar(() -> {
                                initShowLock();
//                            btnOpenPsdDir.setVisible(true);
                                Toast.makeText(getApplication().getStage(), "导入成功", 3000);
                            });
                        }, () -> {
                        });
            } else {
                SBTFxDialog.showMessageDialog(null, "psd文件不存在，请确认后重试！", "温馨提示", () -> {
                }, () -> {
                });
            }
        });
        MenuItem importDir = new MenuItem("导入锁屏文件夹");
        importDir.setOnAction(e -> {
            SBTFxDialog.showMessageDialog(getApplication().getStage(), "导入锁屏文件夹后，原有的文件锁屏文件将会删除！", "温馨提示", "导入", "取消", () -> {
                String path = lockscreenPath.toFile().getPath();

                File chosenDir = CtsFileChooser.getInstance().showOpenDirDialog(primaryStage,"选择文件夹");
                if (chosenDir != null) {
                    System.out.println(chosenDir.getAbsolutePath());
                    String sourcePath = chosenDir.getAbsolutePath();
                    try {
                        if (folderFormat(sourcePath)) {
                            delFolder(path);
                            copyDir(sourcePath, path);
                            AutoSaveUtils.getInstance(themeFileInfo).stopSave();
                            ProgressDialog progressDialog = new ProgressDialog(new Task<Void>() {
                                @Override
                                protected Void call() throws Exception {

                                    new LockstylePsdUtils(themeFileInfo).importLockscreen();
                                    return null;
                                }
                            }, getApplication().getStage(), "正在导入，请稍等……");
                            progressDialog.showProgressBar(() -> {
                                initShowLock();
//                            btnOpenPsdDir.setVisible(true);
                                Toast.makeText(getApplication().getStage(), "导入成功", 2000);
                            });
                        } else {
                            Platform.runLater(() -> {
                                SBTFxDialog.showMessageDialog(getApplication().getStage(), "导入失败，请检查文件夹！", "温馨提示", () -> {
                                }, () -> {
                                });
                            });

//                           Toast.makeText(getApplication().getStage(), "导入失败", 2000);

                        }

                    } catch (Exception e1) {
                        e1.getStackTrace();
                    }

                } else {
                    Platform.runLater(() -> {
                        SBTFxDialog.showMessageDialog(getApplication().getStage(), "导入失败，请检查文件夹！", "温馨提示", () -> {
                        }, () -> {
                        });
                    });
                }
            }, () -> {
            });


        });
        MenuItem openPsdDir = new MenuItem("打开psd文件夹");
        openPsdDir.setOnAction(event -> {

            if (themeFileInfo.getThemeLockscreenPsdFile().exists()) {
                openFile(themeFileInfo.getThemeLockscreenPsdFile().getParentFile());
            } else {
                SBTFxDialog.showMessageDialog(null, "psd文件不存在，请确认后重试！", "温馨提示", () -> {
                }, () -> {
                });
            }
        });
        fileMenu.getItems().add(optModule);
        fileMenu.getItems().add(importDir);
        fileMenu.getItems().add(importLockscreen);
        fileMenu.getItems().add(openPsdDir);
        fileMenu.getItems().add(openErrFile);
        MenuItem to360Menu = new MenuItem("VIVO转360");
        to360Menu.setOnAction(event -> {
            File file = CtsFileChooser.getInstance().showOpenDirDialog(new Stage(), "选择文件夹");
            if (file == null) {
                return;
            }
//            To360(file);
            if (CheckManifestUtils.getInstance().checkUnlockRuleProgress(themeFileInfo, Constants.VIVO, primaryStage, o ->
                    new AlertDialog.Builder(null, "锁屏格式错误")
                            .setMessage(o+"\n请联系锁屏制作人员进行修改")
                            .setOkButton("好的")
                            .build().show())) {
                return;
            }
            ProgressDialog progressFrom = new ProgressDialog(new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    if (file != null) {
                        try {
                            String lockpath = String.valueOf(Paths.get(themeFileInfo.getThemeDir().getPath(), themeFileInfo.getThemeType(), ThemeFileInfo.LOCKSTYLE_NAME, ThemeFileInfo.LOCKSCREEN_NAME));
                            Files.createDirectories(Paths.get(file.getPath()+File.separator+Constants.OS360+File.separator +"code"));
                            Files.createDirectories(Paths.get(file.getPath()+File.separator+Constants.OS360+File.separator+"product"+File.separator+"debug"));
                            Files.createDirectories(Paths.get(file.getPath()+File.separator+Constants.OS360+File.separator+"product"+File.separator+"release"));
                            FileToZip.copy(lockpath, file.getPath()+File.separator+Constants.OS360+File.separator+"code");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        res = IntentCommandUtils.checkIntent(file, themeFileInfo, Constants.OS360);
                    }
                    return null;
                }
            }, primaryStage, "正在检测文件，请稍等……");
            progressFrom.showProgressBar(() -> {
                if (file != null) {
                    Platform.runLater(() -> {
                        if (res) {
                            To360(file, Constants.OS360);
                        } else {
                            new LockstyleIntentDialog().reviseIntent(file, themeFileInfo, Constants.OS360, IntentCommandUtils.getError(), o -> openErrFile.setVisible(true), primaryStage, expressionUtils);
                        }
                    });
                }

            });


        });
        MenuItem toOPPOMenu = new MenuItem("VIVO转OPPO");
        toOPPOMenu.setOnAction(event -> {
            File file = CtsFileChooser.getInstance().showOpenDirDialog(new Stage(), "选择文件夹");
            if (file == null) {
                return;
            }
            if (CheckManifestUtils.getInstance().checkUnlockRuleProgress(themeFileInfo, Constants.VIVO, primaryStage, o ->
                    new AlertDialog.Builder(null, "锁屏格式错误")
                            .setMessage(o+"，\n请联系锁屏制作人员进行修改。")
                            .setOkButton("好的")
                            .build().show())) {
                return;
            }
            ProgressDialog progressCopy = new ProgressDialog(new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    ThemeChangeUtils.getInstance().changeVivo2Oppo(themeFileInfo, Paths.get(file.toString(), Constants.OPPO, "code").toFile(), o -> {
                        openErrFile.setVisible(true);
                        switch (o) {
                            case "1":
                                Toast.makeText(primaryStage, "壁纸大小不正确 跳过 请稍后...", 2000);
                                break;
                            case "2":
                                break;
                            default:
                                Toast.makeText(primaryStage, "转换错误", 2000);
                                break;
                        }
                    });
                    res = IntentCommandUtils.checkIntent(file, themeFileInfo, Constants.OPPO);
                    return null;
                }
            }, primaryStage, "正在校验，请稍等……");
            progressCopy.showProgressBar(() -> {
                if (res) {
                    ProgressDialog progressFrom = new ProgressDialog(new Task<Void>() {
                        @Override
                        protected Void call() throws Exception {
                                ThemeChangeUtils.getInstance().copyManifestFile();
                            return null;
                        }
                    }, primaryStage, "正在转换，请稍等……");
                    progressFrom.showProgressBar(() -> {
                        Toast.makeText(getApplication().getStage(), "转换成功", 3000);
                        Platform.runLater(() -> {
                            if (IntentCommandUtils.getError().size() > 0) {
                                StringBuffer message = new StringBuffer("以下快捷修改失败，具体如下：\n");
                                for (IntentCommand in : IntentCommandUtils.getError()) {
                                    message.append(JSON.toJSON(in) + "\n");
                                }
                                SBTFxDialog.showMessageDialog(primaryStage, message.toString(), "温馨提示");
                            }
                            if (ThemeChangeUtils.isToastNoBG()) {
                                ErrorLogUtils.getInstance().createLog(themeFileInfo, "没有找到正确的壁纸转换为OPPO的壁纸");
                                SBTFxDialog.showMessageDialog(primaryStage, "找不到正确的壁纸进行裁剪\n请将壁纸命名更改为:\ndefault_lock_wallpaper_2400.jpg", "温馨提示");
                            }
                        });
                        try {
                            new LockScreenPackager(Constants.OPPO, Paths.get(file.toString(),Constants.OPPO ,"code"),Paths.get(file.getPath() ,Constants.OPPO ,"product","debug")).pack((types, path) -> {
                            }, (types, path) -> {
                            });
                            Desktop.getDesktop().open(Paths.get(file.getPath() ,Constants.OPPO ,"product","debug").toFile());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                } else {
                    new LockstyleIntentDialog().reviseIntent(file, themeFileInfo, Constants.OPPO,
                            IntentCommandUtils.getError(), o -> openErrFile.setVisible(true), primaryStage, expressionUtils);
                }
            });


        });
        MenuItem uppack = new MenuItem("微乐打包");
        uppack.setDisable(true);
        uppack.setOnAction(event -> {
            String poppath = String.valueOf(Paths.get(themeFileInfo.getResModelFile("lockscreen").getPath(), "vlife"));
            String datapath = String.valueOf(Paths.get(themeFileInfo.getResModelFile("lockscreen").getPath(), "vlife/data"));
            String filepath = String.valueOf(Paths.get(lockscreenPath.toFile().getPath()));
            String lockpath = String.valueOf(Paths.get(themeFileInfo.getThemeDir().getPath(), themeFileInfo.getThemeType(), ThemeFileInfo.LOCKSTYLE_NAME));
            System.out.println(lockpath);
            ProgressDialog progressFrom = new ProgressDialog(new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    try {
                        long _TEN_THOUSAND = 10000;
                        long times = 1000 * _TEN_THOUSAND;
                        long timepath = testSystem(times) / 1000;
                        FileToZip.weileToZip(poppath, filepath, datapath, lockpath, timepath);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            }, primaryStage, "正在打包，请稍等……");
            progressFrom.showProgressBar(() -> {
                getApplication().getStage().close();
                Toast.makeText(getApplication().getStage(), "打包成功，请打包主题查看", 3000);
            });
        });
        CheckMenuItem autoSave = new CheckMenuItem("自动保存");

        toolMenu.getItems().add(to360Menu);
        toolMenu.getItems().add(toOPPOMenu);
        toolMenu.getItems().add(uppack);
        toolMenu.getItems().add(autoSave);
        autoSave.setSelected(true);
        autoSave.selectedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) {
                AutoSaveUtils.getInstance(themeFileInfo).startAutoSave(lockstyleShowUtils);
            } else {
                AutoSaveUtils.getInstance(themeFileInfo).stopSave();
            }
        });
        MenuItem helpItem = new MenuItem("模板说明");
        helpItem.setOnAction(e -> {
            Path configPath = Paths.get(themeFileInfo.getThemeDir().getPath(), themeFileInfo.getThemeType(), ThemeFileInfo.LOCKSTYLE_NAME, "lockstyleConfig.json");
            String str = null;
            try {
                str = new String(Files.readAllBytes(configPath), "UTF-8");
                ModelItem lockScreenModelExplain = new Gson().fromJson(str,
                        new TypeToken<ModelItem>() {
                        }.getType());
                SBTFxDialog.showMessageDialog(null, "制作说明：" + lockScreenModelExplain.getTitle().replace("\\n", "\n") + lockScreenModelExplain.getDescribe().replace("\\n", "\n"), "帮助说明");
            } catch (IOException e2) {
                e2.printStackTrace();
            }

        });
        helpMenu.getItems().add(helpItem);
        menuAll.getMenus().add(fileMenu);
        menuAll.getMenus().add(toolMenu);
        menuAll.getMenus().add(helpMenu);
        toolMenu.setStyle("hover:{-fx-background-color: #716A94;}");

    }

    private void To360(File file, String type) {
        ProgressDialog progressFrom = new ProgressDialog(new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                if (file != null) {
                    IntentCommandUtils.copyFile(Paths.get(file.getPath() + File.separator + type + File.separator + "code").toFile(), themeFileInfo, o -> openErrFile.setVisible(true));
                }
                return null;
            }
        }, primaryStage, "正在转换，请稍等……");

        progressFrom.showProgressBar(() -> {
            if (file != null) {
                Toast.makeText(getApplication().getStage(), "转换成功", 3000);
                Platform.runLater(() -> {
                    if (IntentCommandUtils.getError().size() > 0) {
                        StringBuffer message = new StringBuffer("以下快捷修改失败，具体如下：\n");
                        for (IntentCommand in : IntentCommandUtils.getError()) {
                            message.append(JSON.toJSON(in) + "\n");
                        }
                        SBTFxDialog.showMessageDialog(primaryStage, message.toString(), "温馨提示");
                    }
                });
                try {
                    new LockScreenPackager(type, Paths.get(file.toString(),type ,"code"),Paths.get(file.getPath() ,type ,"product","debug")).pack((types, path) -> {
                    }, (types, path) -> {
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    Desktop.getDesktop().open(Paths.get(file.getPath() ,type ,"product","debug").toFile());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        });
    }

    //复制文件夹
    private void copyDir(String sourcePath, String newPath) throws IOException {
        File file = new File(sourcePath);
        String[] filePath = file.list();

        if (!(new File(newPath)).exists()) {
            (new File(newPath)).mkdir();
        }

        for (int i = 0; i < filePath.length; i++) {
            if ((new File(sourcePath + file.separator + filePath[i])).isDirectory()) {
                copyDir(sourcePath + file.separator + filePath[i], newPath + file.separator + filePath[i]);
            }
            if (new File(sourcePath + file.separator + filePath[i]).isFile()) {
                copyFile(sourcePath + file.separator + filePath[i], newPath + file.separator + filePath[i]);
            }

        }
    }

    //复制文件
    private void copyFile(String oldPath, String newPath) throws IOException {

        File oldFile = new File(oldPath);
        File file = new File(newPath);
        FileInputStream in = new FileInputStream(oldFile);
        FileOutputStream out = new FileOutputStream(file);

        byte[] buffer = new byte[2097152];
        int readByte = 0;
        while ((readByte = in.read(buffer)) != -1) {
            out.write(buffer, 0, readByte);
        }

        in.close();
        out.close();
    }

    //删除文件
    private boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    //删除文件夹
    private boolean delFolder(String folderPath) {
        boolean bl = true;
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            bl = myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bl;
    }

    private boolean folderFormat(String path) {
        boolean bl = true;

        Path xmlPath = Paths.get(path, "manifest.xml");
        try {
            if (themeFileInfo.getThemeType().equals(Constants.OPPO)) {
                switch ((int) expressionUtils.getScreen_height()) {
                    case 2160:
                        xmlPath = Paths.get(path, "2x1", "manifest.xml");
                        break;
                    case 2280:
                        xmlPath = Paths.get(path, "19x9", "manifest.xml");
                        break;
                    case 2340:
                        xmlPath = Paths.get(path, "13x6", "manifest.xml");
                        break;
                    default:
                        xmlPath = Paths.get(path, "manifest.xml");
                        break;
                }
            }
            if (!Files.exists(xmlPath)) {
                bl = false;
            }
            Path date = Paths.get(path, "date");
            if (!Files.exists(date)) {
                date = Paths.get(path, "month");
                if (!Files.exists(date)) {
                    Path date1 = Paths.get(path,"date1");
                    Path date2 = Paths.get(path,"date2");
                    Path month1 = Paths.get(path,"month1");
                    Path month2 = Paths.get(path,"month2");
                    if (!Files.exists(date1) && !Files.exists(date2) && !Files.exists(month1) && !Files.exists(month2)) {
                        bl = false;
                    }

                }
            }
            Path week = Paths.get(path, "week");
            if (!Files.exists(week)) {
               Path week1 = Paths.get(path,"week1");
               Path  week2 = Paths.get(path,"week2");
                if (!Files.exists(week1) && !Files.exists(week2)){
                    bl = false;
                }


            }
            Path time = Paths.get(path, "time");
            if (!Files.exists(time)) {
                Path  time1 = Paths.get(path, "time1");
                Path  time2 = Paths.get(path, "time2");
                if (!Files.exists(time1) && !Files.exists(time2)) {
                    bl = false;
                }


            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return bl;
    }


}
